package com.zut.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zut.base.entity.Directory;
import com.zut.base.entity.Project;
import com.zut.base.entity.Projectanduser;
import com.zut.base.mapper.ProjectMapper;
import com.zut.base.service.IDirectoryService;
import com.zut.base.service.IProjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zut.base.service.IProjectanduserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 项目表 服务实现类
 * </p>
 *
 * @author yyl
 * @since 2021-03-31
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements IProjectService {

    @Autowired
    private ProjectMapper projectMapper;
//    private IProjectService projectServiceImpl;

    @Autowired
    private IDirectoryService directoryServiceImpl;

    @Autowired
    private IProjectanduserService projectanduserServiceImpl;

    @Transactional
    @Override
    public boolean addProjectAndMoudle(Project pro, List<Directory> list,String id) {
        //添加项目表
        int insert = projectMapper.insert(pro);
        for (Directory dir : list){
            dir.setProjectid(pro.getId());
        }
        //添加目录表
        boolean dir = directoryServiceImpl.saveBatch(list);
        //添加项目与用户角色映射表
        Projectanduser projectanduser = new Projectanduser();
        projectanduser.setProjectid(pro.getId());
        projectanduser.setUserid(id);
        projectanduser.setRole("1");
        boolean save = projectanduserServiceImpl.save(projectanduser);
        return insert > 0 && dir && save;
    }

    @Override
    public Map<String,Object> getProjectListById(int page, int count, String dirId, String userId,String type) {
        List<String> ls = null;
        if (!"all".equals(dirId)) {
            ls = new ArrayList<>();
            //查询该目录的所有子目录
            QueryWrapper<Directory> wrapper = new QueryWrapper<>();
            wrapper.eq("parentId", dirId);
            List<Directory> list = directoryServiceImpl.list(wrapper);
            if (list.size() > 0) {
                for (Directory dir : list) {
                    ls.add(dir.getId());
                }
            }
            ls.add(dirId);
        }
        List<HashMap<String,Object>> proList = projectMapper.getProList((page - 1)*7, count, ls, userId, type);
        int num = projectMapper.getProListCount(ls, userId, type);
        Map rs = new HashMap();
        rs.put("list",proList);
        rs.put("count",num);
        return rs;
    }
}
